package com.example.his.controller;

import com.example.his.entity.Fdepartment;
import com.example.his.entity.Sdepartment;
import com.example.his.entity.ShowDpmt;
import com.example.his.mapper.FdpmtMapper;
import com.example.his.mapper.SdpmtMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
@CrossOrigin
@RestController
public class FdpmtController {
    //(由容器自动实现)依赖注入
    @Autowired
    FdpmtMapper fdpmtMapper;
    @Autowired
    SdpmtMapper sdpmtMapper;

    //POST,创建一个父科室实体,ok,小写字段名
    @PostMapping("/api/Fdepartment")
    public ResponseEntity<Fdepartment> add_Fdpmt(@RequestBody Fdepartment fdepartment){
        //持久化参数对象
        //在save之前是没有id的
        fdpmtMapper.save(fdepartment);
        //save后生成了id
        return new ResponseEntity<Fdepartment>(
                fdepartment, HttpStatus.OK
        );
    }

    //DELETE,删除一个父科室实体,ok
    @DeleteMapping("/api/Fdepartment/{Fdid}")
    public ResponseEntity<String> delFdpmt(@PathVariable int Fdid){
        fdpmtMapper.remove(Fdid);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    //PUT,更新一个实体，按照Id更新,ok
    @PutMapping("/api/Fdepartment/{Fdid}")
    public ResponseEntity<Fdepartment> updateFdpmt(@PathVariable int Fdid,@RequestBody Fdepartment fdepartment){
        fdepartment.setFdid(Fdid);
        fdpmtMapper.update(fdepartment);
        return new ResponseEntity<Fdepartment>(fdepartment,HttpStatus.OK);
    }


    //GET,检索实体集合,ok
    @GetMapping("/api/Fdepartment")
    public ResponseEntity<List<Fdepartment>> findAllFdpmt(){
        List<Fdepartment> list= fdpmtMapper.findAll();
        return new ResponseEntity<List<Fdepartment>>(
                list, HttpStatus.OK);
    }
    //GET,根据id查找
    @GetMapping("/api/Fdepartment/{Fdid}")
    public ResponseEntity<Fdepartment> findFdpmtById(@PathVariable  int Fdid){
        Fdepartment fdepartment= fdpmtMapper.load(Fdid);
        return new ResponseEntity<Fdepartment>(
                fdepartment,HttpStatus.OK);
    }

    //根据一级科室
    @GetMapping("/api/departmentList")
    public ResponseEntity<List<ShowDpmt>> ShowDpmt(){
        List<ShowDpmt> listShow = new ArrayList<ShowDpmt>();
        List<Fdepartment> listFdmpt= fdpmtMapper.findAll();
        for(Fdepartment f:listFdmpt){
            int id=f.getFdid();
            List<Sdepartment> listSdpmt=sdpmtMapper.findFmatch(id);
            ShowDpmt a=new ShowDpmt();
            a.setId(id);
            a.setName(f.getFdname());
            a.setDetail(listSdpmt);
            a.setSubAmount(listSdpmt.size());
            listShow.add(a);
        }
        return new ResponseEntity<List<ShowDpmt>>(
                listShow, HttpStatus.OK);

    }

}
